<?php
/**
 * Created by PhpStorm.
 * User: sosyuki
 * Date: 2018/5/15
 * Time: 10:29
 */

namespace Drupal\distribution\Entity;


use Entity;
use EntityFieldQuery;

class Distribution extends Entity {

  public $id;

  public $uid;

  public $pid = 0;

  public $tid = 0;

  public $sid = 0;

  public $created;

  public $changed;

  public $is_new_revision;

  function __construct(array $values = []) {
    $this->is_new_revision = TRUE;
    parent::__construct($values, 'distribution');
  }

  static function getDistribution($uid) {
    $entities = entity_load('distribution', FALSE, ['uid' => $uid]);
    if (!empty($entities)) {
      $entity = reset($entities);
      if ($entity instanceof Distribution) {
        return $entity;
      }
    }
    return new static(['uid' => $uid]);
  }

  static function getTeam(int $uid) {
    $entities = entity_load('distribution', FALSE, ['uid' => $uid]);
    if (!empty($entities)) {
      $entity = reset($entities);
      if ($entity instanceof Distribution) {
        return $entity->tid;
      }
    }
    return -1;
  }

  static function getChilds(array $uids) {
    $list = [];
    foreach ($uids as $uid) {
      $list[] = self::getChild($uid);
    }
    return $list;
  }

  static function getChild(int $uid) {
    $entities = entity_load('distribution', FALSE, ['pid' => $uid]);
    $list = [];
    if (!empty($entities)) {
      foreach ($entities as $entity) {
        if ($entity instanceof Distribution) {
          if (self::checkValidity($entity)) {
            $list[] = $entity;
          }
        }
      }
    }
    return $list;
  }

  /**
   * @param \Drupal\distribution\Entity\Distribution $distribution
   *
   * @return bool
   * 检查绑定有效期
   */
  static function checkValidity(Distribution $distribution) {
    $use = variable_get_value('distribution_validity_use');
    switch ($use) {
      case 'all':
        {
          return TRUE;
          break;
        }
      case 'seconds':
        {
          $number = variable_get_value('distribution_validity_seconds');
          if ($distribution->created + $number > REQUEST_TIME) {
            return TRUE;
          }
          break;
        }
    }
    return FALSE;
  }

  function save() {
    $this->changed = REQUEST_TIME;
    if (empty($this->created)) {
      $this->created = REQUEST_TIME;
    }
    if ($this->uid == $this->pid) {
      return FALSE;
    }
    //检查上家信息 是否存在循环
    if ($this->uid == self::getParent($this->pid)) {
      return FALSE;
    }
    return parent::save();
  }

  static function getParent(int $uid) {
    $entities = entity_load('distribution', FALSE, ['uid' => $uid]);
    if (!empty($entities)) {
      $entity = reset($entities);
      if ($entity instanceof Distribution) {
        if (self::checkValidity($entity)) {
          return $entity->pid;
        }
      }
    }
    return -1;
  }

  function childCount() {
    return count(self::getChild($this->uid));
  }

  /**
   * @return bool
   * @deprecated 弃用 使用 sid 标记来源 无需检测有效期
   */
  function validity() {
    if ($this->created == 0) {
      return FALSE;
    }
    return self::checkValidity($this);
  }

  function orderCount() {
    return self::getOrderCount($this->uid);
  }

  /**
   * @param $uid
   *
   * @return int|mixed
   * @deprecated
   */
  static function getOrderCount($uid) {
    $childs = self::getChild($uid);
    $uids = [];
    foreach ($childs as $child) {
      if ($child instanceof Distribution) {
        $uids[] = $child->uid;
      }
    }
    if (!empty($uids)) {
      $status_ids = ['pending', 'processing', 'completed',];
      $query = new EntityFieldQuery();
      $result = $query->entityCondition('entity_type', 'commerce_order')
        ->entityCondition('bundle', 'commerce_order')
        ->propertyCondition('uid', $uids, 'IN')
        ->propertyCondition('status', $status_ids)
        ->propertyOrderBy('changed', 'DESC')
        ->count()
        ->execute();
      return $result;
    }
    return 0;
  }

}
